package com.android.basiclib.base.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.android.basiclib.base.vm.BaseViewModel
import java.lang.reflect.ParameterizedType

abstract class BaseVVDLazyLoadingFragment<VM : BaseViewModel, VB : ViewBinding> : BaseVMLazyLoadingFragment<VM>() {

    private var _binding: VB? = null
    protected val mBinding: VB
        get() = requireNotNull(_binding) { "ViewBinding对象为空" }

    // 反射创建ViewBinding
    protected open fun createViewBinding() {

        try {
            val clazz: Class<*> = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1] as Class<VB>
            val inflateMethod = clazz.getMethod("inflate", LayoutInflater::class.java)
            _binding = inflateMethod.invoke(null, layoutInflater) as VB
        } catch (e: Exception) {
            e.printStackTrace()
            throw IllegalArgumentException("无法通过反射创建ViewBinding对象")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createViewBinding()
    }

    override fun setContentView(container: ViewGroup?): View {
        return mBinding.root
    }

    override fun getLayoutIdRes(): Int = 0

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}